package app

import (
	"context"
	"encoding/json"
	"errors"
	"strings"

	"gitee.com/leicc/go-app-core/models/im"
	"gitee.com/leicc/go-imsrv-app/app/logic"
	"gitee.com/leicc/go-imsrv-app/app/proto"
	"gitee.com/leicc/go-orm/log"
	"gitee.com/leicc/thirdparty"
	"google.golang.org/grpc"
)

type httpUserSt struct {
	Code int64 `json:"code"`
	Datas logic.UserSt `json:"datas"`
	Msg  string `json:"msg"`
}

//对接第三方平台 需要接入token校验 当前测试专用
func SysToken(data *logic.ArgsRegTokenSt) (*logic.UserSt, error) {
	log.Write(log.DEBUG, data.Token, data.Agent, data.AppId)
	aState := logic.ImAppSt{}
	err := im.NewImApp().GetOne(data.AppId).ToStruct(&aState)
	if err != nil || aState.Appid < 1 {
		return nil, errors.New("请求的应用配置不存在哟！")
	}
	if strings.HasPrefix(aState.Grpcsrv, "http") {
		return _getHttpSrvUser(&aState, data)
	} else {//走GRPC协议
		return _getGrpcSrvUser(&aState, data)
	}
}

//通过http协议对接验证账号数据信息
func _getHttpSrvUser(aState *logic.ImAppSt, data *logic.ArgsRegTokenSt) (*logic.UserSt, error) {
	httpSt := thirdparty.NewHttpRequst()
	httpSt.SetHeader(map[string]string{"User-Agent": data.Agent})
	query  := map[string]string{"token": data.Token}
	body, _:= json.Marshal(query)
	result := httpSt.Request(aState.Grpcsrv, body, "POST")
	if result == nil || len(result) < 1 {
		log.Write(log.ERROR, "请求服务{"+aState.Grpcsrv+"}解析发送未知错误")
		return nil, errors.New("请求服务{"+aState.Grpcsrv+"}解析发送未知错误")
	}
	eState := httpUserSt{}
	if err := json.Unmarshal(result, &eState); err != nil || eState.Code != 0 || eState.Datas.UserId < 1 {
		log.Write(log.ERROR, "请求验证账号信息异常", err, string(result))
		return nil, errors.New("请求验证返回账号信息错误")
	}
	return &eState.Datas, nil
}

//通过rpc校验对接参数数据信息
func _getGrpcSrvUser(aState *logic.ImAppSt, data *logic.ArgsRegTokenSt) (*logic.UserSt, error) {
	conn, err := grpc.Dial(aState.Grpcsrv, grpc.WithInsecure())
	if err != nil {//连接异常的情况
		log.Write(log.ERROR, "连接服务{", aState.Grpcsrv, "}请求异常", err.Error())
		return nil, errors.New("连接服务{"+ aState.Grpcsrv+"}请求异常")
	}
	defer conn.Close()
	client := proto.NewGrpcUCenterServiceClient(conn)
	reqSt  := proto.GetUserRequest{Token: data.Token, Agent: data.Agent}
	res, err := client.GetUser(context.Background(), &reqSt)
	if err != nil || res.Id < 1 {
		log.Write(log.ERROR, "请求grpc服务返回异常{"+aState.Grpcsrv+"}", err)
		return nil, errors.New("请求grpc服务异常,无法操作")
	}
	return &logic.UserSt{UserId: res.Id,
		Nick: res.NickName, Avatar: res.Avatar, Gender: int8(res.Gender)}, nil
}
